/**
 * @(#)ApkTaskController.java 2016年11月11日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.domian.SimulatorInfoVo;
import org.jsbd.boss.domian.channel.BaseResultVo;
import org.jsbd.boss.domian.channel.RetentTaskVo;
import org.jsbd.boss.domian.channel.SmsSyncVo;
import org.jsbd.boss.enums.ResponseEnum;
import org.jsbd.boss.service.ClientManager;
import org.jsbd.boss.service.IChannelTaskService;
import org.jsbd.boss.service.IRetentTaskService;
import org.jsbd.boss.service.IThirdTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 模拟器以及用户任务
 *
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@RequestMapping("/apktask")
@Controller
public class ApkTaskController {
	public static final Logger LOGGER = LoggerFactory.getLogger(ApkTaskController.class);

	@Resource
	private IChannelTaskService channelTaskService;

	@Resource
	private IThirdTaskService thirdTaskService;

	@Resource
	private ClientManager clientManager;

	@Resource
	private IRetentTaskService taskService;

	@ResponseBody
	@RequestMapping("/getTask")
	public void getSimulatorTask(HttpServletResponse response, SimulatorInfoVo simulatorInfoVo) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			String uuid = simulatorInfoVo.getUuid();
			String sysVer = simulatorInfoVo.getSysVer();
			if (StringUtils.isBlank(uuid) || StringUtils.isBlank(sysVer)) {
				resultVo.setMessage("请求参数非法!");
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
			} else {
				resultVo = channelTaskService.getTask(simulatorInfoVo);
			}
		} catch (Exception e) {
			LOGGER.error("获取任务失败", e);
			resultVo.setMessage(e.getMessage());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@ResponseBody
	@RequestMapping("/removeSelfCardImsi")
	public void removeSelfCardImsi(HttpServletResponse response, String imsi) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			channelTaskService.removeImsiRecord(imsi);
		} catch (Exception e) {
			LOGGER.error("删除失败", e);
			resultVo.setMessage(e.getMessage());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	/**
	 *
	 * obtain:获取短信
	 *
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/obtainSms", method = RequestMethod.POST)
	public void obtainSms(String result, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (StringUtils.isBlank(result)) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				resultVo = channelTaskService.smsTask(result);
			}
		} catch (Exception e) {
			resultVo.setMessage(e.getMessage());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
			LOGGER.error("下发短信失败", e);
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	/**
	 *
	 * synsSms:消息同步
	 *
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/syncSms")
	public void synsSms(HttpServletResponse response, SmsSyncVo smsVo) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (smsVo == null || StringUtils.isBlank(smsVo.getOrderId()) || smsVo.getOrderId().indexOf("_") < 0 || StringUtils.isBlank(smsVo.getResultCode())) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				resultVo = channelTaskService.syncSmsTask(smsVo);
			}
		} catch (Exception e) {
			LOGGER.error("短信同步失败", e);
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
			resultVo.setMessage(e.getMessage());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@ResponseBody
	@RequestMapping("/syncSmsCode")
	public void syncSmsCode(HttpServletRequest request, HttpServletResponse response) {
		SmsSyncVo smsVo = getSmsVo(request);
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (smsVo == null || StringUtils.isBlank(smsVo.getImsi()) || StringUtils.isBlank(smsVo.getSmsContent())) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				String resultCode = smsVo.getResultCode();
				if ("1".equals(resultCode)) {
					//0 正常
					smsVo.setResultCode("0");
				}
				resultVo = channelTaskService.syncSmsTask(smsVo);
			}
		} catch (Exception e) {
			LOGGER.error("短信同步失败", e);
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
			resultVo.setMessage(e.getMessage());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	private SmsSyncVo getSmsVo(HttpServletRequest request) {
		InputStream in = null;
		try {
			in = request.getInputStream();
			byte[] data = IOUtils.toByteArray(request.getInputStream());
			if (data == null) {
				return null;
			}
			JSONObject jsonData = JSON.parseObject(new String(data, "UTF-8"));
			SmsSyncVo vo = new SmsSyncVo();
			vo.setBizId(jsonData.getString("bizId"));
			vo.setImsi(jsonData.getString("imsi"));
			vo.setResultCode(jsonData.getInteger("resultCode") + "");
			vo.setSmsContent(jsonData.getString("smsContent"));
			vo.setSms(jsonData.getString("smsContent"));
			return vo;
		} catch (IOException e) {
			LOGGER.error("parse getSmsVo error", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LOGGER.error("Any error msg that u want to write", e);
				}
			}
		}
		return null;
	}

	/**
	 *
	 * syncRetent:同步留存任务
	 *
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param taskInfo
	 */
	@ResponseBody
	@RequestMapping("/syncRetentTask")
	public void syncRetent(HttpServletResponse response, RetentTaskVo taskInfo) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (taskInfo == null || StringUtils.isBlank(taskInfo.getImsi()) || StringUtils.isBlank(taskInfo.getMark())) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				resultVo = channelTaskService.syncRetentTask(taskInfo);
			}
		} catch (Exception e) {
			LOGGER.error("留存任务同步失败", e);
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
			resultVo.setMessage(e.getMessage());
		}
		ResponseUtils.renderJson(response, resultVo.toString());

	}

	@ResponseBody
	@RequestMapping("/syncBrushTask")
	public void syncBrushTask(HttpServletResponse response, RetentTaskVo taskVo) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (taskVo == null || taskVo.getBrushId() == null) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				taskService.syncBrushTask(taskVo);
			}
		} catch (Exception e) {
			LOGGER.error("留存任务同步失败", e);
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
			resultVo.setMessage(e.getMessage());
		}
		ResponseUtils.renderJson(response, resultVo.toString());

	}

	/**
	 *
	 * getVerifyCode:获取短信验证码
	 *
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param mark
	 * @param imsi
	 * @return
	 */
	@RequestMapping(value = "/getVerifyCode")
	@ResponseBody
	public void getVerifyCode(HttpServletResponse response, String mark, String imsi) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			String data = clientManager.getImsiSmsCode(imsi, mark);
			if (StringUtils.isNotBlank(data)) {
				resultVo.setData(data);
			} else {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("获取验证码失败!");
			}
		} catch (Exception e) {
			resultVo.setStatus(ResponseEnum.FAIL.getStatus());
			resultVo.setMessage("获取验证码失败!");
			LOGGER.error("获取验证码失败", e);
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "/sendSms")
	@ResponseBody
	public void sendSms(HttpServletResponse response, String code, String mobile) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			thirdTaskService.sendSms(code, mobile);
		} catch (Exception e) {
			resultVo.setStatus(ResponseEnum.FAIL.getStatus());
			resultVo.setMessage("发送失败!");
			LOGGER.error("发送失败", e);
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}



}
